package gw.com.android.ui.onlive;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.presenter.http.HttpCallback;
import gw.com.android.presenter.http.MyConcernRequest;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.me_concern.AnalystData;
import gw.com.android.utils.ImageUtil;
import gw.com.android.utils.PackStatis;
import gw.com.android.utils.ThreadPool;
import www.com.library.util.DeviceUtil;
import www.com.library.util.NetworkMonitor;

/**
 * @author jett
 * @since 2018-03-07.
 */
public class AutoDiscussActivity extends BaseActivity {

    private final float SCALE = 0.85F;
    private static final int EDIT_MAX = 500;

    @BindView(R.id.discuss_templet_pager)
    RatioViewPager pagers;
    @BindView(R.id.discuss_templet_left)
    View previousPage;
    @BindView(R.id.discuss_templet_right)
    View nextPage;
    @BindView(R.id.discuss_content)
    EditTextWithMaxLimit etContent;
    @BindView(R.id.discuss_clear)
    ImageView ivClear;
    @BindView(R.id.discuss_float_guide)
    View ivFloatGuide;
    @BindView(R.id.tv_count)
    TextView tv_count;

    private DiscussTempletAdapter adapter;
    private DiscussContentHelper contentHelper;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_auto_discuss;
    }

    @Override
    protected void initLayoutView() {
        mTitleBar.setAppTitle(R.string.discuss_auto_title);
        pagers.setPageMargin(DeviceUtil.instance().dip2px(-20, getApplicationContext()));
        pagers.setOffscreenPageLimit(3);
        pagers.setRatio(301 * 1.0F / 410);// 模板 的宽高比例统一定为 301:410
        pagers.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                onPageScroll(position, positionOffset);
            }

            @Override
            public void onPageSelected(int position) {
                onPage(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String text = etContent.getText().toString();
                if (TextUtils.isEmpty(text)) {
                    ivClear.setVisibility(View.GONE);
                } else {
                    ivClear.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        ivFloatGuide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ivFloatGuide.clearAnimation();
                ivFloatGuide.setVisibility(View.GONE);
            }
        });
        startGuideAnim();
        etContent.setMax(EDIT_MAX);
        tv_count.setText(0 + "/" + EDIT_MAX);
        etContent.setTextWatcherCallback(new EditTextWithMaxLimit.TextWatcherCallback() {
            @Override
            public void onDataChange(int current) {
                tv_count.setText(current + "/" + EDIT_MAX);
            }
        });
    }

    private void startGuideAnim() {
        TranslateAnimation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.1F, Animation.RELATIVE_TO_SELF, 0F);
        anim.setDuration(500);
        anim.setInterpolator(new DecelerateInterpolator());
        anim.setRepeatMode(Animation.REVERSE);
        anim.setRepeatCount(20);
        anim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                ObjectAnimator alpha = ObjectAnimator.ofFloat(ivFloatGuide, "alpha", 1, 0);
                alpha.setDuration(300);
                alpha.start();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        ivFloatGuide.startAnimation(anim);
    }

    @Override
    protected void initViewData() {
        TradeResultData data = getIntent().getParcelableExtra("tradeResult");
        if (data == null) {
            finish();
            return;
        }
        double value = -1;
        try {
            value = Double.parseDouble(data.amount);
        } catch (NumberFormatException ignore) {
        }
        if (value == 0) {
            contentHelper = new DiscussContentHelper(DiscussContentHelper.STATE_NONE);
        } else {
            contentHelper = new DiscussContentHelper(data.profit ? DiscussContentHelper.STATE_PROFIT : DiscussContentHelper.STATE_LOSS);
        }
        adapter = new DiscussTempletAdapter(DiscussTemplet.buildTemplets(this, data));
        pagers.setAdapter(adapter);
        switchContent();
    }

    private void onPageScroll(int position, float offset) {
        View pager1 = adapter.getPagerView(position);
        View pager2 = adapter.getPagerView(position + 1);
        float s1 = SCALE + (1 - SCALE) * (1 - offset);
        if (pager1 != null) {
            pager1.setScaleX(s1);
            pager1.setScaleY(s1);
        }
        float s2 = SCALE + (1 - SCALE) * offset;
        if (pager2 != null) {
            pager2.setScaleX(s2);
            pager2.setScaleY(s2);
        }
    }

    private void onPage(int position) {
        if (position <= 0) {
            previousPage.setVisibility(View.GONE);
        } else {
            previousPage.setVisibility(View.VISIBLE);
        }
        if (position >= adapter.getCount() - 1) {
            nextPage.setVisibility(View.GONE);
        } else {
            nextPage.setVisibility(View.VISIBLE);
        }
    }

    @OnClick(R.id.discuss_confirm)
    void sendDiscuss() {
        PackStatis.getToService("clickConfirmBask", "Trade", null, null);
        if (!NetworkMonitor.hasNetWork()) {
            return;
        }
        final String content = etContent.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            showToastPopWindow(AppMain.getAppString(R.string.home_discuss_add_content_null_2));
            return;
        }
        showLoading();
        ThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
//                send(content);
                getAllAnalyst(content);
            }
        });
    }

    // 封装方法，获取当前所有分析师
    private MyConcernRequest myConcernRequest;

    /**
     * 这里要插播一个步骤，判定当前用户是不是分析师,取出所有分析师，然后遍历,。。。野路子野路子
     *
     * @param content
     */
    private void getAllAnalyst(final String content) {
        if (myConcernRequest == null) {
            myConcernRequest = new MyConcernRequest();
        }
        myConcernRequest.getAllAnalystList(new HttpCallback<List<AnalystData>>() {
            @Override
            public void onSuccess(List<AnalystData> result) {
                // 获取成功之后，判断当前用户是不是
                String currentLoginPhone = GTConfig.instance().mCurLoginPhone;//手机号登录？
                String currentLoginName = GTConfig.instance().mCurName;//逐个对比，当前登录的用户名（可能是交易账户，可能是手机号码，现在只考虑交易账户） 和分析师的交易账户有没有相同的
                Log.d("currentLoginTag", currentLoginPhone + "-" + currentLoginName);

                String analystNo = "";
                boolean ifAnalyst = false;
                for (int i = 0; i < result.size(); i++) {
                    if (currentLoginName.equals(result.get(i).accountNo)) {// 一旦发现当前用户是分析师，那么直接发起 分析师发帖，isAnalyst为true
                        ifAnalyst = true;
                        analystNo = result.get(i).userNo;
                        break;
                    }
                }
                if (ifAnalyst)
                    Log.d("getAllAnalystTag2", "分析师大佬开始晒单");
                else
                    Log.d("getAllAnalystTag2", "普通用户开始晒单");

                send(content, ifAnalyst, analystNo);
            }

            @Override
            public void onFailure(Exception e) {
                Log.d("getAllAnalyst", "Exception:" + e.getLocalizedMessage());
            }
        });
    }

    private StringBuffer imgSize;//图片尺寸，多张图用 英文逗号分隔

    private void send(String content, boolean ifAnalyst, String analystNo) {
        File file = buildTempletImage();

        List<File> fileList = new ArrayList<>(1);
        fileList.add(file);
        imgSize = new StringBuffer();
        imgSize.append("");
        imgSize.append(",");
        new DiscussAddRequest(content, ifAnalyst, analystNo, true, fileList, new DiscussAddRequest.OnDiscussCallback() {
            @Override
            public void onSuccess() {
                hideLoading();
                showToastPopWindow(AppMain.getAppString(R.string.discuss_auto_sucess));
                setResult(Activity.RESULT_OK);
                finish();
            }

            @Override
            public void onFailure() {
                hideLoading();
                showToastPopWindow(AppMain.getAppString(R.string.home_discuss_add_fail));
            }
        }).execute(imgSize.toString());
    }

    public static void getWidthHeightOfImg(String srcPath) {
        // 该对象为图片缩放操作对象
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，该参数为true时，只会在读取图片的宽高 而不产生bitmap 无论图片大小 都用他读取。
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);//此时返回bm为空
        //读取后一定要 设置成false;
        newOpts.inJustDecodeBounds = false;
        //获取 原图图片的长和宽
        int realw = newOpts.outWidth;
        int realh = newOpts.outHeight;
        Log.d("getWidthHeightOfImgTag", "" + realw + "-" + realh);
    }

    private File buildTempletImage() {
        if (adapter == null || pagers == null) {
            return null;
        }
        View view = adapter.getPagerView(pagers.getCurrentItem());
        if (view == null) {
            return null;
        }
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Matrix matrix = new Matrix();
        int width = view.getWidth();
        // 控制图片大小为 700 * 954  大约为150+ Kb
        float scale = 700 * 1.0F / width;
        if (scale > 1) {
            scale = 1;
        }
        matrix.postScale(scale, scale);
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache(), 0, 0, view.getWidth(), view.getHeight(), matrix, true);

        bitmap = ImageUtil.addWaterMark(bitmap);

        String path = ImageUtil.getNewPhotoPath();
        ImageUtil.compress(bitmap, path, Bitmap.CompressFormat.PNG, 100);
        view.setDrawingCacheEnabled(false);
        return new File(path);
    }

    @OnClick(R.id.discuss_templet_left)
    void previousPage(View view) {
        pagers.setCurrentItem(pagers.getCurrentItem() - 1);
    }

    @OnClick(R.id.discuss_templet_right)
    void nextPage(View view) {
        pagers.setCurrentItem(pagers.getCurrentItem() + 1);
    }

    @OnClick(R.id.discuss_clear)
    void clearContent() {
        etContent.setText("");
        PackStatis.getToService("clickDelete2", "circle", null, null);
    }

    @OnClick(R.id.discuss_switch)
    void switchContent() {
        if (contentHelper != null) {
            String content = contentHelper.acquireContent();
            etContent.setText(content);
            etContent.setSelection(content.length());
        }
        PackStatis.getToService("clickChange", "circle", null, null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ivFloatGuide.clearAnimation();
        contentHelper.saveUsed();
    }

    private class DiscussTempletAdapter extends PagerAdapter {

        private List<DiscussTemplet> templets;
        private SparseArray<View> children = new SparseArray<>();

        DiscussTempletAdapter(List<DiscussTemplet> templets) {
            this.templets = templets;
        }

        View getPagerView(int position) {
            return children.get(position);
        }

        private DiscussTemplet getTemplet(int position) {
            if (templets != null && position >= 0 && position < templets.size()) {
                return templets.get(position);
            }
            return null;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = children.get(position);
            if (view == null) {
                DiscussTemplet templet = getTemplet(position);
                if (templet != null) {
                    view = templet.createView();
                    children.put(position, view);
                }
            }
            if (view != null) {
                if (position != 0) {
                    view.setScaleX(SCALE);
                    view.setScaleY(SCALE);
                }
                container.addView(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            }
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getCount() {
            return templets == null ? 0 : templets.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

    }

}
